﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Telerik.WebControls;
using System.Data.SqlClient;
using EM.Repository.utility;



namespace EM.Administration.ChangePassword 
{
    public partial class cp : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            Authentication ua = new Authentication();
            ua.CheckRolePageAuthentication(9, Authentication.RedirectionURLTypes.LoginPage);
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            SqlCommand cmd = new SqlCommand();
            DbHelper srv = new DbHelper();

            if (IsOldPasswordRight())
            {
                if (txtNewPassport.Text == txtReNewPassport.Text)
                {
                    string sSQL = "";
                    sSQL = " UPDATE TBLUSER SET USERPASS = @USERPASS";
                    sSQL += " WHERE USERCODE =@USERCODE";

                    cmd.CommandText = sSQL;
                    cmd.Parameters.Add("@USERCODE", SqlDbType.NVarChar).Value = Session["USERCODE"].ToString();
                    cmd.Parameters.Add("@USERPASS", SqlDbType.NVarChar).Value = txtNewPassport.Text.Trim();

                    srv.ExecuteNonQuery(cmd);
                    
                    Page.ClientScript.RegisterStartupScript(typeof(string), "alert", "javascript:alert('Şifreniz başarı ile değiştirildi')", true);    
                }
                else
                {
                    Page.ClientScript.RegisterStartupScript(typeof(string), "alert", "javascript:alert('Şifre ve şifre Tekrar Aynı Olmak Zorunda')", true);    
                }
            }
            else
            {
                Page.ClientScript.RegisterStartupScript(typeof(string), "alert", "javascript:alert('Şifreniz hatalı')", true);
            }
            
        }


        private bool IsOldPasswordRight()
        {
            bool Result = false;

            SqlCommand cmd = new SqlCommand();
            DbHelper srv = new DbHelper();

            string sSQL = "";

            sSQL = " SELECT USERPASS ";
		    sSQL += " FROM TBLUSER ";
            sSQL += " WHERE USERCODE =@USERCODE";
            sSQL += " AND USERPASS =@USERPASS";

            cmd.CommandText = sSQL;
            cmd.Parameters.Add("USERCODE", SqlDbType.NVarChar).Value = Session["USERCODE"].ToString();
            cmd.Parameters.Add("USERPASS", SqlDbType.NVarChar).Value = txtPassword.Text;

            DataTable dt = srv.GetDataTable(cmd, "");

            if (dt.Rows.Count>0)
            {
                Result = true;
            }


            return Result;
        }
        
    }
}